/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/core/{{modules}}/service/impl/{{entities@SQL}}ServiceImpl.java.hbs
 */
// @SkipOverwrite
package cn.ibizlab.core.ad.service.impl;

import cn.ibizlab.core.ad.domain.SysOrganizationalRole;
import cn.ibizlab.core.authorization.domain.SysRoleMember;
import cn.ibizlab.core.authorization.service.SysRoleMemberService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cn.ibizlab.core.authentication.constants.AuthenticationConstant.MEMBER_TYPE_ORGANIZATIONAL_ROLE;

/**
 * 实体[用户组] 服务对象接口实现
 */
@Slf4j
@Service("SysOrganizationalRoleService")
public class SysOrganizationalRoleServiceImpl extends AbstractSysOrganizationalRoleService {

    @Autowired
    SysRoleMemberService sysRoleMemberService;

    @Override
    public boolean create(SysOrganizationalRole et) {
        setOU(et);
        return super.create(et);
    }

    @Override
    public boolean createBatch(List<SysOrganizationalRole> list) {
        list.forEach(this::setOU);
        return super.createBatch(list);
    }

    @Override
    public boolean update(SysOrganizationalRole et) {
        setOU(et);
        return super.update(et);
    }

    @Override
    public boolean updateBatch(List<SysOrganizationalRole> list) {
        list.forEach(this::setOU);
        return super.updateBatch(list);
    }

    private void setOU(SysOrganizationalRole et){
        et.setOrganizationalUnitId(et.getDepartmentId()==null?et.getOrganizationId():et.getDepartmentId());
    }

    @Override
    public boolean remove(SysOrganizationalRole et) {
        sysRoleMemberService.remove(Wrappers.<SysRoleMember>lambdaQuery().eq(SysRoleMember::getMemberUid,et.getId()).eq(SysRoleMember::getMemberType,MEMBER_TYPE_ORGANIZATIONAL_ROLE));
        return super.remove(et);
    }

    @Override
    public SysOrganizationalRole roleAuth(SysOrganizationalRole dto) {
        List<Map<String,Object>> srfActionParams = dto.getOrDefault("srfactionparam",new ArrayList<>());
        if(!srfActionParams.isEmpty()){
            srfActionParams.forEach(param ->
                sysRoleMemberService.save( new SysRoleMember()
                        .setRoleId((String)param.get("srfkey"))
                        .setMemberType(MEMBER_TYPE_ORGANIZATIONAL_ROLE)
                        .setMemberUid(dto.getId())
                        .setMemberName(dto.getName()))
            );
        }
        return super.roleAuth(dto);
    }
}